// pages/release/release.js
import Toast from 'tdesign-miniprogram/toast/index';
import {
  apiPublishComment
} from '../../../utils/http/api'
import evn from "../../../utils/http/evn"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    url: '',
    originFiles: [],
    gridConfig: {
      column: 3,
      width: 200,
      height: 200,
    },
    config: {
      count: 1,
    },
    form: {
      title: '',
      content: '',
      commentFiles: []
    },
    userInfo: {},
    disabled: true,
    visible: false,
    schoolId: 0,
    schoolName: '',
    proId: '',
    proNameCn: '',
    type: 0,
    eduPlanName: ''
  },


  // 跳转个人信息页
  goPersonal() {
    wx.reLaunch({
      url: '/pages/personal/personal',
    })
  },

  closeDialog() {
    this.setData({
      visible: false,
    });
    // 返回上一页
    wx.navigateBack()
  },


  onChangeT(e) {
    let title = this.data.form.title
    let content = this.data.form.content
    this.setData({
      'form.title': e.detail.value,
      disabled: title === '' || content === '' ? true : false
    })
  },

  onChangeC(e) {
    let title = this.data.form.title
    let content = this.data.form.content
    this.setData({
      'form.content': e.detail.value,
      disabled: title === '' || content === '' ? true : false
    })
  },
  handleSuccess(e) {
    const {
      files
    } = e.detail;
    //如果文件大小超过1m .则压缩文件在1m内
    //循环处理每个文件
    files.forEach((item) => {
      if (item.size > 1024 * 1024) {
        wx.compressImage({
          src: item.url, // 图片路径
          quality: 80, // 压缩质量
          success: (res) => {
            //增加这个图片进originFiles
            this.setData({
              originFiles: this.data.originFiles.concat({
                url: res.tempFilePath,
                name: item.name,
                type: item.type
              }),
            });
          }
        })
      } else {
        //不重复的增加进originFiles
        if (this.data.originFiles.findIndex((v) => v.url === item.url) === -1) {
          this.setData({
            originFiles: this.data.originFiles.concat(item),
          });
        }
      }

    });
  },
  handleRemove(e) {
    const {
      index
    } = e.detail;
    const {
      originFiles
    } = this.data;
    originFiles.splice(index, 1);
    this.setData({
      originFiles,
    });
  },
  handleClick(e) {
    //压缩图片大小宽度在1024内
  },



  // 上传图片 
  upImages(item) {
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: evn.dev.baseUrl + '/oss/upload',
        filePath: item.url,
        name: 'file',
        success: (res) => {
          var resData = JSON.parse(res.data)
          if (resData.code != 200) {
            wx.showModal({
              title: '图片不通过',
              content: resData.msg || '图片违规，请重新选择图片',
              showCancel: false,
              confirmText: '我知道了'
            });
            this.setData({
              loadingFlag: false,
              originFiles: [],
            })
            this.data.form.commentFiles = []
            reject()
            return
          }
          this.data.form.commentFiles.push(resData.fileUrl);
          resolve(); // 表示上传完成
        },
        fail: (err) => {
          reject(err); // 表示上传失败
        }
      });
    });
  },

  // ...existing code...
  // 发布讨论
  async insertCommentInfo() {
    this.setData({
      loadingFlag: true
    })
    let originFiles = this.data.originFiles;
    try {
      // 如果有图片待上传，展示全局加载提示
      if (originFiles && originFiles.length > 0) {
        wx.showLoading({
          title: '图片上传中...',
          mask: true
        });
      }
      // 上传所有图片并获取上传完成的Promise数组
      let uploadPromises = originFiles.map((item) => this.upImages(item));
      await Promise.all(uploadPromises); // 等待所有图片上传完成
      // 上传完成后提示
      if (originFiles && originFiles.length > 0) {
        wx.hideLoading();
        wx.showToast({
          title: '发布完成',
          icon: 'success',
          duration: 1500
        });
      }
      let filesStr = "";
      if (this.data.form.commentFiles.length > 0) {
        filesStr = this.data.form.commentFiles.join(',')
      }
      let params = {
        objectId: this.data.schoolId ? Number(this.data.schoolId) : 0,
        title: this.data.form.title,
        content: this.data.form.content,
        wechatUserId: this.data.userInfo.id,
        pics: filesStr,
        type: 1
      };
      if (params.title && params.content) {
        // 所有图片上传完成后，执行apiInsertCommentInfo方法
        let result = await apiPublishComment(params);
        if (result.code === 200) {
          // 发布成功，取消加载状态
          this.setData({
            loadingFlag: false
          });
          wx.navigateBack()
        } else if (result.code === 7) {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '内容含有敏感词，请重新填写',
            theme: 'warning',
            direction: 'column',
          });
          this.setData({
            loadingFlag: false
          })
        } else if (result.code === 500 && result.msg && result.msg.indexOf('评论内容不安全') !== -1) {
          wx.showModal({
            title: '评论不通过',
            content: result.msg,
            showCancel: false,
            confirmText: '我知道了'
          });
          this.setData({
            loadingFlag: false
          })
        } else {
          Toast({
            context: this,
            selector: '#t-toast',
            message: result.msg || '评论提交失败',
            theme: 'warning',
            direction: 'column',
          });
          this.setData({
            loadingFlag: false
          })
        }
      } else {
        if (!params.title) {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '请输入标题',
            theme: 'warning',
            direction: 'column',
          });
        } else {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '请输入内容',
            theme: 'warning',
            direction: 'column',
          });
        }
        this.setData({
          loadingFlag: false
        })
      }

    } catch (error) {
      // 发生错误时关闭加载提示
      try {
        wx.hideLoading();
      } catch (e) {}
      this.setData({
        loadingFlag: false
      })
    }

  },
  // ...existing code...


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (wx.getStorageSync('userInfo') == null) {
      wx.reLaunch({
        url: '/pages/login/login',
      })
    }

    this.setData({
      schoolName: options.schoolName,
      schoolId: options.schoolId,
      type: options.type,
      eduPlanName: options.eduPlanName,
      userInfo: wx.getStorageSync('userInfo')
    })


  },

  //过滤html标签
  filterHtmlTags(html) {
    if (!html) return '';
    return html.replace(/<[^>]+>/g, '').replace(/&nbsp;/g, ' ').trim();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})